package academic.ui.server;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletConfig;



public class AppServer {

		private volatile static AppServer AppServerInstance = new AppServer();
		

		private static ServletConfig servletconfig;


		private static String logDir;

		private volatile boolean appserverstarted  = false;

		private volatile boolean initializing = false;
		
		private AppServer()
		{
		}

		public static void setServletconfig(ServletConfig config) {
			servletconfig = config;
		}
		
		public static AppServer getAppServerInstance()
		{
			return getAppServerInstance(servletconfig);
		}


		public ServletConfig getServletconfig() {
			return servletconfig;
		}

		public static void applyProperties() throws IOException
		{
			String configPropPath = servletconfig.getServletContext().getRealPath("/") + "config.properties";
			Properties sysProps = new Properties(System.getProperties());
			try
			{
				sysProps.load(new BufferedInputStream(new FileInputStream(configPropPath)));
			}
			catch (FileNotFoundException ex)
			{
				System.out.println("(Warning) system.properties file not found at " + configPropPath);
			}
			System.setProperties(sysProps);
			
			logDir = servletconfig.getServletContext().getRealPath(System.getProperty("logpath"));
		}

		public static AppServer getAppServerInstance(ServletConfig config) {
			
			if (servletconfig == null)
			{
				synchronized (AppServer.class)
				{
					setServletconfig(config);
					if (!AppServerInstance.isInitialized() && !AppServerInstance.isInitializing())
						AppServerInstance.initializeServer();
				}
			}
			return AppServerInstance;
			
			
		}


		private void initializeServer() {
			
			initializing=true;
			try {
				applyProperties();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			initializing  = false;
			appserverstarted = true;
		}


		private boolean isInitializing() {
			return initializing;
		}


		public boolean isInitialized()
		{
			return this.appserverstarted;
		}

		public String getLogPath() {
			return logDir;
		}
		
		

}
